#include "video.h"

namespace YQ {

VideoSize::VideoSize (int width, int height)
	: width (width), height (height)
{ }


Mat
getAnImageFromVideo (VideoCapture &video) noexcept (false)
{
	if (!video.isOpened())
		throw logic_error ("video未打开");
	Mat img;
	video >> img;
	return img;
}

VideoSize
getVideoSize (VideoCapture &video) noexcept (false)
{
	if (!video.isOpened())
		throw logic_error ("video未打开");
	const Mat &img = getAnImageFromVideo (video);
	return VideoSize (img.cols, img.rows);
}

VideoSize
getCameraSize (VideoCapture &camera) noexcept (false)
{
	return getVideoSize (camera);
}

VideoSize
getCameraSize (VideoCapture &&camera) noexcept (false)
{
	VideoCapture video = camera;
	return getCameraSize (video);
}

VideoCapture
getDefaultCamera() noexcept (false)
{
	vector<int>id = getAvailableCameraId();
	if (id.size() == 0)
		throw runtime_error ("未检测到摄像头");
	return VideoCapture (id[0]);
}


vector<int>
getAvailableCameraId()
{
	constexpr int max_camera_id = 10;
	using namespace cv::utils::logging;
	const LogLevel old = getLogLevel();
	setLogLevel (LOG_LEVEL_SILENT);
	
	vector<int> id;
	for (int i = 0; i < max_camera_id; ++i) {
		VideoCapture video (i);
		if (video.isOpened()) {
			if (!getAnImageFromVideo (video).empty())
				id.push_back (i);
		}
		video.release();
	}
	setLogLevel (old);
	return id;
}

}